package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/region")
public class RegionController {
    @Autowired
    private IRegionService regionService;

    /**
     * 跳转地区页面
     * @return
     */
    @RequestMapping("/list")
    public String list(){
        return "region/list";
    }

    /**
     * 通过地区的下属地区
     * 如果parentId为null,则查询出根地区
     * @param parentId 上级地区的id
     * @return 地区数据
     */
    @RequestMapping("/selectByParentId")
    @ResponseBody
    public Object selectByParentId(Long parentId,Boolean flag){
        List<Region> regions = regionService.selectByParentId(parentId);
        if (flag != null) {
            return regions;
        }
        ArrayList<Map> list = new ArrayList<>();
        for (Region region : regions) {
            list.add(region.toTreeMap());
        }
        return list;
    }
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Region region){
        regionService.saveOrUpdate(region);
        return new JSONResult();
    }

    @RequestMapping("/updateStateById")
    @ResponseBody
    public Object updateStateById(Long id,Integer state){
        regionService.updateStateById(id,state);
        return new JSONResult();
    }
}
